'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');

var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

exports.default = updateById;

var _record = require('./helpers/record');

var _findById = require('./findById');

var _findById2 = _interopRequireDefault(_findById);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/* eslint-disable no-param-reassign */

function updateById(model, tc, opts) {
  if (!model || !model.modelName || !model.schema) {
    throw new Error('First arg for Resolver updateById() should be instance of Mongoose Model.');
  }

  if (!tc || tc.constructor.name !== 'TypeComposer') {
    throw new Error('Second arg for Resolver updateById() should be instance of TypeComposer.');
  }

  const findByIdResolver = (0, _findById2.default)(model, tc);

  const outputTypeName = `UpdateById${tc.getTypeName()}Payload`;
  const outputType = tc.constructor.schemaComposer.getOrCreateTC(outputTypeName, t => {
    t.addFields({
      recordId: {
        type: 'MongoID',
        description: 'Updated document ID'
      },
      record: {
        type: tc.getType(),
        description: 'Updated document'
      }
    });
  });

  const resolver = new tc.constructor.schemaComposer.Resolver({
    name: 'updateById',
    kind: 'mutation',
    description: 'Update one document: ' + '1) Retrieve one document by findById. ' + '2) Apply updates to mongoose document. ' + '3) Mongoose applies defaults, setters, hooks and validation. ' + '4) And save it.',
    type: outputType,
    args: (0, _extends3.default)({}, (0, _record.recordHelperArgs)(tc, (0, _extends3.default)({
      recordTypeName: `UpdateById${tc.getTypeName()}Input`,
      requiredFields: ['_id'],
      isRequired: true
    }, opts && opts.record))),
    resolve: (() => {
      var _ref = (0, _asyncToGenerator3.default)(function* (resolveParams) {
        const recordData = resolveParams.args && resolveParams.args.record || {};

        if (!(typeof recordData === 'object')) {
          return Promise.reject(new Error(`${tc.getTypeName()}.updateById resolver requires args.record value`));
        }

        if (!recordData._id) {
          return Promise.reject(new Error(`${tc.getTypeName()}.updateById resolver requires args.record._id value`));
        }

        resolveParams.args._id = recordData._id;
        delete recordData._id;

        // We should get all data for document, cause Mongoose model may have hooks/middlewares
        // which required some fields which not in graphql projection
        // So empty projection returns all fields.
        resolveParams.projection = {};

        let doc = yield findByIdResolver.resolve(resolveParams);

        if (resolveParams.beforeRecordMutate) {
          doc = yield resolveParams.beforeRecordMutate(doc, resolveParams);
        }

        if (!doc) {
          throw new Error('Document not found');
        }

        if (recordData) {
          doc.set(recordData);
          yield doc.save();
        }

        return {
          record: doc,
          recordId: tc.getRecordIdFn()(doc)
        };
      });

      return function resolve(_x) {
        return _ref.apply(this, arguments);
      };
    })()
  });

  return resolver;
}